package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.DefaultConstant;
import cn.huiyunche.base.service.form.BVehicleTypeForm;
import cn.huiyunche.base.service.interfaces.BVehicleTypeService;
import cn.huiyunche.base.service.mappers.BVehicleTypeMapper;
import cn.huiyunche.base.service.mappers.ext.BVehicleTypeExtMapper;
import cn.huiyunche.base.service.model.BVehicleType;
import cn.huiyunche.base.service.model.BVehicleTypeExample;
import cn.huiyunche.base.service.query.BVehicleTypeQueryConditions;
import cn.huiyunche.base.service.vo.BVehicleTypeVo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: cn.huiyunche.service.base.tms.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 下午4:04
 */
@Service
public class BVehicleTypeServiceImpl implements BVehicleTypeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BVehicleTypeServiceImpl.class);

    @Autowired
    private BVehicleTypeMapper bVehicleTypeMapper;

    @Autowired
    private BVehicleTypeExtMapper bVehicleTypeExtMapper;

    @Override
    public Long getIdByConditions(String vehicleCode, String vehicleName, String vehicleDesc) {
        LOGGER.info("getIdByConditions params : {}, {}, {}", vehicleCode, vehicleName, vehicleDesc);

        if (StringUtils.isBlank(vehicleCode)) {
            LOGGER.error("getIdByConditions param vehicleCode must not be null");
            throw new IllegalArgumentException("车型编号不能为空");
        }
        if (StringUtils.isBlank(vehicleName)) {
            LOGGER.error("getIdByConditions param vehicleName must not be null");
            throw new IllegalArgumentException("车型名称不能为空");
        }
        if (StringUtils.isBlank(vehicleDesc)) {
            LOGGER.error("getIdByConditions param vehicleDesc must not be null");
            throw new IllegalArgumentException("车型说明不能为空");
        }

        BVehicleTypeExample example1 = new BVehicleTypeExample();
        example1.createCriteria().andTypeCodeEqualTo(vehicleCode).andTypeNameEqualTo(vehicleName).andDescripitionEqualTo(vehicleDesc);

        BVehicleTypeExample example2 = new BVehicleTypeExample();
        example2.createCriteria().andTypeCodeEqualTo(vehicleCode);

        List<BVehicleType> list = bVehicleTypeMapper.selectByExample(example1);
        if (CollectionUtils.isEmpty(list)) {
            list = bVehicleTypeMapper.selectByExample(example2);
            if (CollectionUtils.isNotEmpty(list)) {
                BVehicleType vehicleType = list.get(0);
                vehicleType.setTypeName(vehicleName);
                vehicleType.setDescripition(vehicleDesc);
                bVehicleTypeMapper.updateByPrimaryKeySelective(vehicleType);
                return vehicleType.getId();
            }
        } else {
            return list.get(0).getId();
        }

        BVehicleType vehicleType = new BVehicleType();
        vehicleType.setTypeCode(vehicleCode);
        vehicleType.setTypeName(vehicleName);
        //默认驾照类型
        vehicleType.setLicenseType(DefaultConstant.DEFAULT_VEHICLE_LICENSE);
        vehicleType.setDescripition(vehicleDesc);
        bVehicleTypeMapper.insertSelective(vehicleType);

        return vehicleType.getId();
    }

    @Override
    public List<BVehicleType> selectByFuelTypeId(Integer fuelTypeId) {
        LOGGER.info("BVehicleTypeServiceImpl.selectByFuelCode param : {}", fuelTypeId);

        if (null == fuelTypeId) {
            LOGGER.error("BVehicleTypeServiceImpl.selectByFuelCode fuelTypeId must not be null ");
            throw new IllegalArgumentException("燃油主键不能为空");
        }

        BVehicleTypeExample example = new BVehicleTypeExample();
        example.createCriteria().andFuelTypeIdEqualTo(fuelTypeId);

        return bVehicleTypeMapper.selectByExample(example);
    }

    @Override
    public Long add(BVehicleTypeForm form, BindingResult br) {
        LOGGER.info("BVehicleTypeServiceImpl.add params : {}", form);

        if (null == form) {
            LOGGER.error("BVehicleTypeServiceImpl.add param form must not be null ");
            throw new IllegalArgumentException("车型类型表单不能为空");
        }

        //验证表单
        verificationForm(br);

        //验证车型编码唯一性
        List<BVehicleType> list = this.selectByTypeCode(form.getTypeCode());
        if (CollectionUtils.isNotEmpty(list)) {
            LOGGER.error("BVehicleTypeServiceImpl.add list is not empty ");
            throw new BusinessException("车型编号已经存在！");
        }

        BVehicleType vehicleType = new BVehicleType();
        BeanUtils.copyProperties(form, vehicleType);

        bVehicleTypeMapper.insertSelective(vehicleType);

        return vehicleType.getId();
    }

    @Override
    public BVehicleType selectByPrimaryId(Long id) {
        LOGGER.info("BVehicleTypeServiceImpl.selectByPrimaryId param : {}", id);

        if (null == id) {
            LOGGER.error("BVehicleTypeServiceImpl.selectByPrimaryId param id must not be null");
            throw new IllegalArgumentException("主键不能为空");
        }

        return bVehicleTypeMapper.selectByPrimaryKey(id);
    }

    private void verificationForm(BindingResult br) {

        if (null == br) {
            LOGGER.error("BVehicleTypeServiceImpl.verificationForm error br is null");
            throw new IllegalArgumentException("BindingResult is null");
        }

        if (br.hasErrors()) {
            List<ObjectError> list = br.getAllErrors();
            LOGGER.error("DRouteServiceImpl.add error : {}", list.get(0).getDefaultMessage());
            throw new IllegalArgumentException(list.get(0).getDefaultMessage());
        }
    }

    @Override
    public Long update(BVehicleTypeForm form, BindingResult br) {
        LOGGER.info("BVehicleTypeServiceImpl.update param : {}", form);

        if (null == form) {
            LOGGER.error("BVehicleTypeServiceImpl.update param form must not be null ");
            throw new IllegalArgumentException("车型类型表单不能为空");
        }

        //验证表单
        verificationForm(br);

        //验证车型编码唯一性
        List<BVehicleType> list = this.selectByTypeCode(form.getTypeCode());
        if (CollectionUtils.isNotEmpty(list)) {
            BVehicleType vehicleType = list.get(0);
            if (list.size() > 1) {
                if (null != form.getId() && form.getId().longValue() != vehicleType.getId().longValue()) {
                    LOGGER.error("BVehicleTypeServiceImpl.add list is not empty ");
                    throw new BusinessException("车型编号已经存在！");
                }
            }
        }

        BVehicleType vehicleType = new BVehicleType();
        BeanUtils.copyProperties(form, vehicleType);

        bVehicleTypeMapper.updateByPrimaryKeySelective(vehicleType);

        return vehicleType.getId();

    }

    @Override
    public Map<String, Object> selectListByConditions(PageVo pageVo, BVehicleTypeQueryConditions conditions) {
        LOGGER.info("BVehicleTypeServiceImpl.selectListByConditions params : {}, {}", pageVo, conditions);

//        if( null == pageVo ){
//            LOGGER.error("BVehicleTypeServiceImpl.selectListByConditions param pageVo must not be null ");
//            throw new IllegalArgumentException("分页信息不能为空");
//        }
        if (null == conditions) {
            LOGGER.error("BVehicleTypeServiceImpl.selectListByConditions param conditions must not be null ");
            throw new IllegalArgumentException("查询条件信息不能为空");
        }

        Map<String, Object> map = new HashMap<>();

        String orderByClause = null;
        if (null != pageVo) {
            orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " update_time DESC";
        }

        BVehicleTypeExample example = new BVehicleTypeExample();
        BVehicleTypeExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(conditions.getTypeCode())) {
            criteria.andTypeCodeLikeInsensitive("%" + conditions.getTypeCode() + "%");
        }
        if (StringUtils.isNotBlank(conditions.getTypeName())) {
            criteria.andTypeNameLikeInsensitive("%" + conditions.getTypeName() + "%");
        }
        if (StringUtils.isNotBlank(conditions.getLicenseType())) {
            criteria.andLicenseTypeEqualTo(conditions.getLicenseType());
        }
        if (null != conditions.getFuelTypeId()) {
            criteria.andFuelTypeIdEqualTo(conditions.getFuelTypeId());
        }
        if (null != conditions.getFuelConsumption()) {
            criteria.andFuelConsumptionGreaterThanOrEqualTo(conditions.getFuelConsumption());
        }

        if (null != pageVo) {
            pageVo.setTotalRecord(bVehicleTypeExtMapper.countByExample(example));
            example.setLimitStart(pageVo.getStartIndex());
            example.setLimitEnd(pageVo.getPageSize());
            example.setOrderByClause(orderByClause);
        }

        List<BVehicleTypeVo> list = bVehicleTypeExtMapper.selectByExample(example);
        map.put("list", list);

        if (null != pageVo) {
            map.put("page", pageVo);
        }

        return map;
    }

    @Override
    public List<BVehicleType> selectByTypeCode(String typeCode) {
        LOGGER.info("BVehicleTypeServiceImpl.selectByTypeCode param : {}", typeCode);

        if (StringUtils.isBlank(typeCode)) {
            LOGGER.error("BVehicleTypeServiceImpl.selectByTypeCode param typeCode must not be null ");
            throw new IllegalArgumentException("车型编号不能为空");
        }

        BVehicleTypeExample example = new BVehicleTypeExample();
        example.createCriteria().andTypeCodeEqualTo(typeCode);

        return bVehicleTypeMapper.selectByExample(example);
    }
}
